package gui.engraving;

import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.border.BevelBorder;
import javax.swing.border.SoftBevelBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;

import java.awt.Color;
import java.awt.ComponentOrientation;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;
import com.jgoodies.forms.factories.FormFactory;








import entities.Employee;
import entities.EngraveComment;
import entities.ProductionOrder;
import net.miginfocom.swing.MigLayout;

import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import javax.swing.ImageIcon;

import utilities.Services;

import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.SwingConstants;

import java.awt.SystemColor;
import java.awt.Font;


/**
 * @author Idan
 * This is the GUI class for the engrave report
 */
public class EngravingReportPanel extends JPanel
{
	private JTextField orderIDTextField;
	private JTextField dateTextField;
	private JTextField typeTextField;
	private JTextField diopterTextField;
	private JTextField sideATextField;
	private JTextField sideBTextFieldEditable;
	private JTextField sideATextFieldEditable;
	private JTextField sideBTextField;
	private ArrayList<Object> listOfEmployees = new ArrayList<Object>();
	private ArrayList<Object> listOfComments = new ArrayList<Object>();
	private JComboBox employeeComboBox;
	private JComboBox shiftComboBox;
	private JTextArea remarksTextArea;
	private JPanel remarksJPanel;
	private JButton confirmButton;
	private EngravingPanel myPanel;
	private String lastOrderIdTyped = "";
	private JTextField line1TextField;
	private JLabel maxcharLabel;
	private JLabel charCounterLabel;
	private JTextField line2TextField;
	private JLabel label_3;
	private JLabel label_4;
	private JComboBox comments1JComboBox;
	private JLabel label_5;
	private JComboBox comments2JComboBox;
	private JLabel freeTextLabel;
	//private Date todayCalendar;
	private String today;
	//private final DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
	private ProductionOrder currentOrderID;
	private boolean waitForDBApproval=false;
	private int currentQuantity;
	private JButton button;
	private JLabel label_6;
	private JTextField rawMaterial;
	
	public EngravingReportPanel(EngravingPanel tabbedPanel)
	{
		setBackground(new Color(173, 216, 230));
		this.myPanel = tabbedPanel;
		//todayCalendar = Calendar.getInstance().getTime();
		//today = dateFormat.format(todayCalendar);
		today = utilities.Services.getToday();
		setLayout(new FormLayout(new ColumnSpec[] {
				FormFactory.RELATED_GAP_COLSPEC,
				ColumnSpec.decode("default:grow"),
				FormFactory.RELATED_GAP_COLSPEC,},
			new RowSpec[] {
				FormFactory.RELATED_GAP_ROWSPEC,
				RowSpec.decode("fill:default:grow"),
				RowSpec.decode("top:20dlu:grow"),
				FormFactory.RELATED_GAP_ROWSPEC,}));
		
		JPanel innerPanel = new JPanel(){@Override
			public void paintComponent(Graphics g) {
	        Graphics2D g2d = (Graphics2D) g;
	        Color color1 = getBackground();
	        Color color2 = color1.darker();
	        int w = getWidth();
	        int h = getHeight(); 
	        GradientPaint gp = new GradientPaint(
	                0, 0, color1,
	                0, h, color2);

	        g2d.setPaint(gp);
	        g2d.fillRect(0, 0, w, h);
	        }};
		innerPanel.setBackground(new Color(173, 216, 230));
		TitledBorder border1 = new TitledBorder(null, "דוח ייצור", TitledBorder.LEADING, TitledBorder.TOP, null, null);
		 border1.setTitleJustification(TitledBorder.RIGHT);
		innerPanel.setBorder(new TitledBorder(null, "\u05D3\u05D5\u05D7 \u05D9\u05D9\u05E6\u05D5\u05E8", TitledBorder.RIGHT, TitledBorder.TOP, null, new Color(59, 59, 59)));
		add(innerPanel, "2, 2, center, fill");
		innerPanel.setLayout(new MigLayout("", "[100px:n,grow][][100px:n,grow][][100px:n,grow][]", "[][][][][][150px:n,grow][][][][]"));
		
		orderIDTextField = new JTextField();
		orderIDTextField.setFont(new Font("Tahoma", Font.PLAIN, 13));
		orderIDTextField.setHorizontalAlignment(SwingConstants.RIGHT);
		orderIDTextField.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) 
			{
				// Assume enter was pressed.
				String order = orderIDTextField.getText();
				if (order.length() > 7)
				{
					order = order.substring(3); // remove the first 3 characters
					orderIDTextField.setText(order);
				}
				employeeComboBox.requestFocus();
			}
		});
		orderIDTextField.addFocusListener(new FocusAdapter()
		{
			@Override
			public void focusLost(FocusEvent arg0)
			{
				
				//Assume OrderID was typed, try and get order data from DB.
				if (orderIDTextField.getText().equals(""))
				{
					// Field is empty, do nothing.
				}
				else
				{
					
						getOrderData();
					
				}
				
				
			}
			
			
			
			
		});
		innerPanel.add(orderIDTextField, "cell 4 0,growx");
		orderIDTextField.setColumns(8);
		
		JLabel orderIdLabel = new JLabel("פק\"ע:");
		orderIdLabel.setFont(new Font("Tahoma", Font.PLAIN, 13));
		innerPanel.add(orderIdLabel, "cell 5 0,alignx center");
		
		shiftComboBox = new JComboBox();
		shiftComboBox.setModel(new DefaultComboBoxModel(new String[] {"בוקר", "ערב"}));
		innerPanel.add(shiftComboBox, "cell 0 1,growx");
		((JLabel)shiftComboBox.getRenderer()).setHorizontalAlignment(JLabel.RIGHT);
		
		JLabel shiftLabel = new JLabel("משמרת:");
		shiftLabel.setFont(new Font("Tahoma", Font.PLAIN, 13));
		innerPanel.add(shiftLabel, "cell 1 1,alignx trailing");
		
		employeeComboBox = new JComboBox();
		employeeComboBox.setModel(new DefaultComboBoxModel(new String[] {""}));
		employeeComboBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) 
			{
				line1TextField.requestFocus();
			}
		});
		innerPanel.add(employeeComboBox, "cell 2 1,growx");
		
		JLabel label = new JLabel("עובד ייצור:");
		label.setFont(new Font("Tahoma", Font.PLAIN, 13));
		innerPanel.add(label, "cell 3 1");
		
		
		
		
		dateTextField = new JTextField();
		dateTextField.setFont(new Font("Tahoma", Font.PLAIN, 13));
		dateTextField.setHorizontalAlignment(SwingConstants.RIGHT);
		dateTextField.setBackground(Color.LIGHT_GRAY);
		dateTextField.setEditable(false);
		innerPanel.add(dateTextField, "cell 4 1,growx");
		dateTextField.setColumns(8);
		dateTextField.setText(today);

		
		JLabel dateLabel = new JLabel("תאריך:");
		dateLabel.setFont(new Font("Tahoma", Font.PLAIN, 13));
		innerPanel.add(dateLabel, "cell 5 1");
		
		diopterTextField = new JTextField();
		diopterTextField.setFont(new Font("Tahoma", Font.PLAIN, 13));
		diopterTextField.setHorizontalAlignment(SwingConstants.RIGHT);
		diopterTextField.setBackground(Color.LIGHT_GRAY);
		diopterTextField.setEditable(false);
		innerPanel.add(diopterTextField, "cell 0 2,alignx right");
		diopterTextField.setColumns(3);
		
		JLabel diopterLabel = new JLabel("דיופטר:");
		diopterLabel.setFont(new Font("Tahoma", Font.PLAIN, 13));
		innerPanel.add(diopterLabel, "cell 1 2");
		
		line2TextField = new JTextField();
		line2TextField.setFont(new Font("Tahoma", Font.PLAIN, 13));
		line2TextField.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) 
			{
				rawMaterial.requestFocus();
			}
		});
		innerPanel.add(line2TextField, "flowx,cell 2 2,alignx right");
		line2TextField.setColumns(3);
		
		label_3 = new JLabel("-");
		innerPanel.add(label_3, "cell 2 2");
		
		line1TextField = new JTextField();
		line1TextField.setFont(new Font("Tahoma", Font.PLAIN, 13));
		line1TextField.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e)
			{
				line2TextField.requestFocus();
			}
		});
		line1TextField.setHorizontalAlignment(SwingConstants.RIGHT);
		innerPanel.add(line1TextField, "cell 2 2,alignx right");
		line1TextField.setColumns(3);
		
		JLabel lineLabel = new JLabel(":Line");
		lineLabel.setFont(new Font("Tahoma", Font.PLAIN, 13));
		innerPanel.add(lineLabel, "cell 3 2");
		
		typeTextField = new JTextField();
		typeTextField.setFont(new Font("Tahoma", Font.PLAIN, 13));
		typeTextField.setBackground(Color.LIGHT_GRAY);
		typeTextField.setEditable(false);
		innerPanel.add(typeTextField, "cell 4 2,growx");
		typeTextField.setColumns(8);
		
		JLabel typeLabel = new JLabel("סוג עדשה:");
		typeLabel.setFont(new Font("Tahoma", Font.PLAIN, 13));
		innerPanel.add(typeLabel, "cell 5 2");
		
		sideBTextFieldEditable = new JTextField();
		sideBTextFieldEditable.setFont(new Font("Tahoma", Font.PLAIN, 13));
		sideBTextFieldEditable.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e)
			{
				if (sideBTextFieldEditable.getText().equals("0"))
					sideBTextFieldEditable.setText("");
			}
		});
		sideBTextFieldEditable.setHorizontalAlignment(SwingConstants.RIGHT);
		sideBTextFieldEditable.setText("0");
		innerPanel.add(sideBTextFieldEditable, "flowx,cell 0 3,alignx right");
		sideBTextFieldEditable.setColumns(3);
		
		JLabel sideBLabel = new JLabel("צד 2:");
		sideBLabel.setFont(new Font("Tahoma", Font.PLAIN, 13));
		innerPanel.add(sideBLabel, "cell 1 3");
		
		sideATextFieldEditable = new JTextField();
		sideATextFieldEditable.setFont(new Font("Tahoma", Font.PLAIN, 13));
		sideATextFieldEditable.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0)
			{
				if (sideATextFieldEditable.getText().equals("0"))
					sideATextFieldEditable.setText("");
			}
		});
		sideATextFieldEditable.setHorizontalAlignment(SwingConstants.RIGHT);
		sideATextFieldEditable.setText("0");
		sideATextFieldEditable.setBackground(Color.WHITE);
		innerPanel.add(sideATextFieldEditable, "flowx,cell 2 3,alignx right");
		sideATextFieldEditable.setColumns(3);
		
		JLabel label_1 = new JLabel("/");
		innerPanel.add(label_1, "cell 2 3");
		
		sideATextField = new JTextField();
		sideATextField.setFont(new Font("Tahoma", Font.PLAIN, 13));
		sideATextField.setHorizontalAlignment(SwingConstants.RIGHT);
		sideATextField.setBackground(Color.LIGHT_GRAY);
		sideATextField.setEditable(false);
		innerPanel.add(sideATextField, "cell 2 3,alignx right");
		sideATextField.setColumns(3);
		
		JLabel sideALabel = new JLabel("צד 1:");
		sideALabel.setFont(new Font("Tahoma", Font.PLAIN, 13));
		innerPanel.add(sideALabel, "cell 3 3,alignx trailing");
		
		JLabel label_2 = new JLabel("/");
		innerPanel.add(label_2, "cell 0 3");
		
		sideBTextField = new JTextField();
		sideBTextField.setFont(new Font("Tahoma", Font.PLAIN, 13));
		sideBTextField.setHorizontalAlignment(SwingConstants.RIGHT);
		sideBTextField.setBackground(Color.LIGHT_GRAY);
		sideBTextField.setEditable(false);
		innerPanel.add(sideBTextField, "cell 0 3,alignx right");
		sideBTextField.setColumns(3);
		
		remarksJPanel = new JPanel(){@Override
			public void paintComponent(Graphics g) {
	        Graphics2D g2d = (Graphics2D) g;
	        Color color1 = getBackground();
	        Color color2 = color1.darker();
	        int w = getWidth();
	        int h = getHeight(); 
	        GradientPaint gp = new GradientPaint(
	                0, 0, color1,
	                0, h, color2);

	        g2d.setPaint(gp);
	        g2d.fillRect(0, 0, w, h);
	        }};
		remarksJPanel.setBackground(new Color(173, 216, 230));
		TitledBorder border2 = new TitledBorder(null, "הערות לדו''ח", TitledBorder.LEADING, TitledBorder.TOP, null, null);
		border2.setTitleJustification(TitledBorder.RIGHT);
		
		rawMaterial = new JTextField();
		rawMaterial.setFont(new Font("Tahoma", Font.PLAIN, 13));
		
		innerPanel.add(rawMaterial, "cell 4 3,growx");
		rawMaterial.setColumns(10);
		
		label_6 = new JLabel("חומר גלם:");
		label_6.setFont(new Font("Tahoma", Font.PLAIN, 13));
		innerPanel.add(label_6, "cell 5 3");
		remarksJPanel.setBorder(new TitledBorder(null, "\u05D4\u05E2\u05E8\u05D5\u05EA \u05DC\u05D3\u05D5''\u05D7", TitledBorder.RIGHT, TitledBorder.TOP, null, new Color(59, 59, 59)));
		innerPanel.add(remarksJPanel, "cell 0 5 3 5,grow");
		remarksJPanel.setLayout(new MigLayout("", "[216px,grow]", "[][][][120px,grow][]"));
		
		comments1JComboBox = new JComboBox();
		comments1JComboBox.setModel(new DefaultComboBoxModel(new String[] {""}));
		remarksJPanel.add(comments1JComboBox, "flowx,cell 0 0,growx");
		
		label_4 = new JLabel("הערה:");
		label_4.setFont(new Font("Tahoma", Font.PLAIN, 13));
		remarksJPanel.add(label_4, "cell 0 0,alignx right");
		
		freeTextLabel = new JLabel("טקסט חופשי:");
		freeTextLabel.setFont(new Font("Tahoma", Font.PLAIN, 13));
		remarksJPanel.add(freeTextLabel, "cell 0 2,alignx center");
		
		JScrollPane scrollPane = new JScrollPane();
		remarksJPanel.add(scrollPane, "cell 0 3,grow");
		
		remarksTextArea = new JTextArea();
		remarksTextArea.setFont(new Font("Courier New", Font.PLAIN, 13));
		remarksTextArea.setLineWrap(true);
		remarksTextArea.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
		remarksTextArea.getDocument().addDocumentListener(new DocumentListener() 
		{
			
			@Override
		    public void changedUpdate(DocumentEvent e)
			{
		        update();
		    }  

			@Override
			public void insertUpdate(DocumentEvent arg0)
			{
				
				update();
			}

			@Override
			public void removeUpdate(DocumentEvent arg0)
			{
				
				update();
			}
			
			public void update() 
		    {
				charCounterLabel.setText(String.valueOf(remarksTextArea.getText().length()));
				
				if (remarksTextArea.getText().length() > 150)
				{
					charCounterLabel.setForeground(Color.RED);;
				}
				else
				{
					charCounterLabel.setForeground(Color.BLACK);
				}
		    }
		});
		scrollPane.setViewportView(remarksTextArea);
		
		charCounterLabel = new JLabel("0");
		charCounterLabel.setFont(new Font("Tahoma", Font.PLAIN, 13));
		charCounterLabel.setHorizontalAlignment(SwingConstants.RIGHT);
		remarksJPanel.add(charCounterLabel, "flowx,cell 0 4,alignx right");
		
		maxcharLabel = new JLabel("/150");
		maxcharLabel.setFont(new Font("Tahoma", Font.PLAIN, 13));
		remarksJPanel.add(maxcharLabel, "cell 0 4,alignx right");
		
		comments2JComboBox = new JComboBox();
		comments2JComboBox.setModel(new DefaultComboBoxModel(new String[] {""}));
		remarksJPanel.add(comments2JComboBox, "flowx,cell 0 1,growx");
		
		label_5 = new JLabel("הערה:");
		label_5.setFont(new Font("Tahoma", Font.PLAIN, 13));
		remarksJPanel.add(label_5, "cell 0 1,alignx right");
		
		confirmButton = new JButton("דווח על ייצור");
		confirmButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
		confirmButton.setIcon(new ImageIcon(EngravingReportPanel.class.getResource("/graphics/createReportPencil.png")));
		confirmButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
			}
		});
		confirmButton.addMouseListener(new MouseAdapter() 
		{
			@Override
			public void mouseClicked(MouseEvent arg0)
			{
				
				if (isEverythingValid())
				{
					//Create order report
					//System.out.println("++++Creating a new report");
					createProductionReport();
				}

				
				
			}
		});
		innerPanel.add(confirmButton, "cell 4 9,alignx center");
		
		button = new JButton("יציאה");
		button.setFont(new Font("Tahoma", Font.PLAIN, 13));
		button.setIcon(new ImageIcon(EngravingReportPanel.class.getResource("/graphics/exit.png")));
		button.addMouseListener(new MouseAdapter()
		{
			@Override
			public void mouseClicked(MouseEvent arg0) 
			{
				Object[] options = {"כן","לא"};
        		int n = JOptionPane.showOptionDialog(myPanel, "האם ברצונך לצאת מהמערכת?","אישור יציאה", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options,"");
        		
        		if (n==0)
        		{
        			if (myPanel.engravingClient != null)
                    {
                      try
                      {
                    	  myPanel.engravingClient.close();
                      }
                      catch (Exception ignore)
                      {}
                     }
            		
            		System.exit(0);
        		}
        		
			}
		});
		add(button, "2, 3, center, top");
	}

	/**
	 * Initialize the GUI data
	 */
	public void setVariables(ArrayList<Object> response)
	{
		// break the response array lists to local array lists.
		ArrayList<Object> localListOfEmpoyees = (ArrayList<Object>) response.get(1);
		ArrayList<Object> localListOfComments = (ArrayList<Object>) response.get(2);
		
		int employeeCounter = Integer.parseInt(localListOfEmpoyees.get(0).toString());
		listOfEmployees.add(employeeCounter);
		
		int commentCounter = Integer.parseInt(localListOfComments.get(0).toString());
		listOfComments.add(commentCounter);
		
		while (employeeCounter>0)
		{
			Employee employee = (Employee)localListOfEmpoyees.get(employeeCounter);
			listOfEmployees.add(employee);
			employeeComboBox.addItem(Services.createObject(employee.getEmployeeName()));
			employeeCounter--;
		}
		
		while (commentCounter>0)
		{
			EngraveComment comment = (EngraveComment)localListOfComments.get(commentCounter);
			listOfComments.add(comment);
			comments1JComboBox.insertItemAt(Services.createObject(comment.getComment()),1);
			comments2JComboBox.insertItemAt(Services.createObject(comment.getComment()),1);
			commentCounter--;
		}
		
		((JLabel)comments1JComboBox.getRenderer()).setHorizontalAlignment(JLabel.RIGHT);
		((JLabel)comments2JComboBox.getRenderer()).setHorizontalAlignment(JLabel.RIGHT);
		// TODO set shift time
		
		
	}
	
	/**
	 * Fetch order data from the server
	 */
	private void getOrderData()
	{
		// Attempt to get order data from DBS
		ArrayList<Object> response = new ArrayList<Object>();
		ArrayList<Object> message = new ArrayList<Object>();
		
		if (Services.isNumeric(orderIDTextField.getText()))
			{
				
				message.add("getOrderIdData");
				message.add(orderIDTextField.getText());
				
			//	loadingGraphicsLabel.setVisible(true);
			//	loadingLabel.setVisible(true);
				
				try
				{
					response = myPanel.engravingClient.call(message);
					
					
					// handle data
					String mySQLReply = response.get(1).toString();
					
					if (mySQLReply.equalsIgnoreCase("valid"))
					{
						
						// Handle order data
					
						ProductionOrder order = (ProductionOrder)response.get(2);
						currentQuantity = order.getQuantity();
						if (order.getStatusID()>2)
						{
							// Order report is already complete
					
							clearFields();
							
							JOptionPane.showMessageDialog(myPanel.myEngravingFrame,
								    "כבר הופק דוח ייצור עבור פק''ע זו.","שגיאה",JOptionPane.ERROR_MESSAGE);
							orderIDTextField.setText("");
					}
						else
						{
							// Display Data
							//dateTextField.setText(order.getDateAsString());
							
							typeTextField.setText(order.getType());
							String sideA = String.valueOf(order.getQuantity() - order.getSideA());
							String sideB = String.valueOf(order.getQuantity() - order.getSideB());
							
							
							diopterTextField.setText(String.valueOf(order.getDiopter()));
							currentOrderID = order;
							if ( Integer.parseInt(sideA) > 0 )
							{
								sideATextField.setText(sideA);
								sideATextFieldEditable.setText(sideA);
							}
							else
							{
								sideATextField.setText("0");
								sideATextFieldEditable.setText("0");
							}
							
							if ( Integer.parseInt(sideB) > 0 )
							{
								sideBTextField.setText(sideB);
								sideBTextFieldEditable.setText(sideB);
							}
							else
							{
								sideBTextField.setText("0");
								sideBTextFieldEditable.setText("0");
							}
						}
						
					}
					else
					{
						if (mySQLReply.equalsIgnoreCase("invalid"))
						{
							// Display no order was found error
							JOptionPane.showMessageDialog(myPanel.myEngravingFrame,
								    "פק''ע לא נמצאה במערכת.","שגיאה",JOptionPane.ERROR_MESSAGE);
							clearFields();
						}
						else
							if(mySQLReply.equalsIgnoreCase("SQL Failed"))
							{
								// Display SQL Error
								JOptionPane.showMessageDialog(myPanel.myEngravingFrame,
									    "ארעה שגיאה בבסיס הנתונים.","שגיאה",JOptionPane.ERROR_MESSAGE);
							}
						
					}
					
					
				} catch (Exception e)
				{

					//e.printStackTrace();
				
				}
				
		
				
				
			}
		else
		{
			// Prompt error
			JOptionPane.showMessageDialog(myPanel.myEngravingFrame,
				    "פק''ע אינה ערך מספרי תקין","שגיאה",JOptionPane.ERROR_MESSAGE);
			// clear orderID text field
			orderIDTextField.setText("");
		}
		
		
	}
	
	/**
	 * Clear GUI fields
	 */
	private void clearFields() 
	{
		
		dateTextField.setText(today);
		typeTextField.setText("");
		sideATextField.setText("");
		sideBTextField.setText("");
		diopterTextField.setText("");
		remarksTextArea.setText("");
		sideATextFieldEditable.setText("0");
		sideBTextFieldEditable.setText("0");
		line1TextField.setText("");
		line2TextField.setText("");
		comments1JComboBox.setSelectedIndex(0);
		comments2JComboBox.setSelectedIndex(0);
		rawMaterial.setText("");
		employeeComboBox.setSelectedIndex(0);
		shiftComboBox.setSelectedIndex(0);
	}
	
	/**
	 * Test for input validity
	 */
	
	private boolean isEverythingValid()
	{
		if (orderIDTextField.getText().equals(""))
		{
			JOptionPane.showMessageDialog(myPanel.myEngravingFrame,
				    "יש להקליד מספר פק''ע.","שגיאה",JOptionPane.ERROR_MESSAGE);
			return false;
		}
		else
		if (rawMaterial.getText().equals(""))
		{
			JOptionPane.showMessageDialog(myPanel.myEngravingFrame,
				    "יש להקליד אצוות חומר גלם.","שגיאה",JOptionPane.ERROR_MESSAGE);
			return false;
		}
		else
		if (typeTextField.getText().equals(""))
		{
			// No order data was loaded, which means this is a report for an orderid that doesn't exist
			JOptionPane.showMessageDialog(myPanel.myEngravingFrame,
				    "לא ניתן ליצור דו''ח עבור פק''ע שאינה קיימת במערכת.","שגיאה",JOptionPane.ERROR_MESSAGE);
			return false;
		}
		else
		if (sideATextField.getText().equals("0") && sideBTextField.getText().equals("0") )
		{
			JOptionPane.showMessageDialog(myPanel.myEngravingFrame,
				    "בוצעה כבר חריטה עבור פק''ע זו, יש לבצע הפרדה.","שגיאה",JOptionPane.ERROR_MESSAGE);
			return false;
		}
		else
		if (sideATextFieldEditable.getText().equals("0") && sideBTextFieldEditable.getText().equals("0"))
		{
			JOptionPane.showMessageDialog(myPanel.myEngravingFrame,
				    "יש להקליד כמות עדשות שנחרטו.","שגיאה",JOptionPane.ERROR_MESSAGE);
			return false;
		}
		else
		if ((line1TextField.getText().equals("") && line2TextField.getText().equals("") ) || (line1TextField.getText().equals("0") && line2TextField.getText().equals("0") ))
		{
			JOptionPane.showMessageDialog(myPanel.myEngravingFrame,
				    "יש להקליד ליין עליו התבצעה החריטה.","שגיאה",JOptionPane.ERROR_MESSAGE);
			return false;
		}
		else
		if (!Services.isNumeric(sideATextFieldEditable.getText()) || !Services.isNumeric(sideBTextFieldEditable.getText()) || sideATextFieldEditable.getText().startsWith("-") || sideBTextFieldEditable.getText().startsWith("-") )
		{
			JOptionPane.showMessageDialog(myPanel.myEngravingFrame,
				    "ערכי הכמות שהוקלדו אינם תקינים.","שגיאה",JOptionPane.ERROR_MESSAGE);
			return false;
		}
		else
		if (employeeComboBox.getSelectedIndex() == 0)
		{
			//error select employee
			JOptionPane.showMessageDialog(myPanel.myEngravingFrame,
				    "יש לבחור שם עובד מדווח.","שגיאה",JOptionPane.ERROR_MESSAGE);
			return false;
				
		}
		else
		{
		
			int sideAEditable = Integer.parseInt(sideATextFieldEditable.getText());
			int sideA = Integer.parseInt(sideATextField.getText());
			int sideBEditable = Integer.parseInt(sideBTextFieldEditable.getText());
			int sideB = Integer.parseInt(sideBTextField.getText());
			
			if (sideAEditable > sideA || sideBEditable > sideB )
			{
				JOptionPane.showMessageDialog(myPanel.myEngravingFrame,
					    "ערכי הכמות שהוקלדו גבוהים מהכמות שבפק''ע.","שגיאה",JOptionPane.ERROR_MESSAGE);
				return false;
			}
			else
			if (Integer.parseInt(charCounterLabel.getText()) > 150 )
			{
				JOptionPane.showMessageDialog(myPanel.myEngravingFrame,
					    "אורך ההערה אינו יכול לעלות על 150 תווים.","שגיאה",JOptionPane.ERROR_MESSAGE);
				return false;
			}
			
		}
		return true;
	}
	
	/**
	 * Create an engrave report
	 */
	private void createProductionReport()
	{
		
		ArrayList<Object> message = new ArrayList<Object>();
		ArrayList<Object> response = new ArrayList<Object>();
		
		// Create order entity
		ProductionOrder newReport = new ProductionOrder();
		newReport.setDiopter(Float.parseFloat(diopterTextField.getText()));
		newReport.setQuantity(currentQuantity);
		newReport.setEmployee(employeeComboBox.getSelectedItem().toString());
		// get the employee ID for the selected employee
		for (int index =1; index<(int)listOfEmployees.get(0);index++)
		{
			if (((Employee)listOfEmployees.get(index)).getEmployeeName().equalsIgnoreCase(employeeComboBox.getSelectedItem().toString()))
			{
				newReport.setEmployeeID( ((Employee)listOfEmployees.get(index)).getID() );
				break;
			}
					
		}

		newReport.setOrderID(Integer.parseInt(orderIDTextField.getText()));
		newReport.setEngraveDateAsString(dateTextField.getText());
		newReport.setRawMaterial(rawMaterial.getText());

		
		newReport.setShift(shiftComboBox.getSelectedIndex()+1);
		String reportLine = new String();

		if (line1TextField.getText().equals("") || line2TextField.getText().equals("") )
		{
			
			reportLine = line1TextField.getText();
			reportLine = reportLine + line2TextField.getText();
		}
		else
		{
			if (!Services.isNumeric(line1TextField.getText()) || !Services.isNumeric(line2TextField.getText()))
			{
				JOptionPane.showMessageDialog(myPanel.myEngravingFrame,
					    "ליין ייצור חייב להיות מספר.","שגיאה",JOptionPane.ERROR_MESSAGE);
				clearFields();
				return;
			}
			else
			{
				if (line1TextField.getText().equals("0") || line2TextField.getText().equals("0") )
				{
					reportLine = line1TextField.getText().equals("0")? "" : line1TextField.getText();
					String temp = line2TextField.getText().equals("0")?"":line2TextField.getText();
					reportLine = reportLine + temp;
				}
				else
				{
					reportLine = line2TextField.getText();
					reportLine = reportLine + "-";
					reportLine = reportLine + line1TextField.getText();
				}
			}
		}
		newReport.setLine(reportLine);
		newReport.setType(typeTextField.getText());
		newReport.setReportSideA(Integer.parseInt(sideATextFieldEditable.getText()));
		newReport.setReportSideB(Integer.parseInt(sideBTextFieldEditable.getText()));
		newReport.setCommentid1(comments1JComboBox.getSelectedIndex());
		newReport.setCommentid2(comments2JComboBox.getSelectedIndex());
		newReport.setEngraveRemarks(remarksTextArea.getText());		
		newReport.setStatusID(2);
		message.add("newEngraveReport");
		message.add(newReport);
		
		
		// Send to server
		try
		{
	
			
			if (sideATextField.getText().equals(sideATextFieldEditable.getText()) && sideBTextField.getText().equals(sideBTextFieldEditable.getText()))
			{
				// completed the entire quantity in the order
				waitForDBApproval = true;
			
				
			}
		
			
			response = myPanel.engravingClient.call(message);
			
			if (response.get(0).toString().equalsIgnoreCase("Valid"))
			{
				JOptionPane.showMessageDialog(myPanel.myEngravingFrame,
					    "דיווח על הייצור בוצע.","אישור",JOptionPane.INFORMATION_MESSAGE);
				
				
				// initialize the seperate tab and remove the order from the list
				if (waitForDBApproval)
				{
					
					// remove order from list of orders
        			myPanel.listOfOrdersPanel.removeFromTable(orderIDTextField.getText());
					
					Object[] options = {"כן","לא"};
	        		int q = JOptionPane.showOptionDialog(myPanel.myEngravingFrame, "הפק''ע הושלמה. האם ברצונך לדווח על הפרדה?","ביצוע הפרדה", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options,"");
					
	        		if (q==0)
	        		{
	        			myPanel.seperatePanel.initializeAfterReport(newReport, currentOrderID);
	        			myPanel.setSelectedIndex(3);
	        			
	        			
	        		}
	        		else
	        		{
	        			// Do nothing
	        		
	        		}
					
					waitForDBApproval=false;
				}
				
				// add row to the list of engrave reports tab
				newReport.setEngraveID((int)(response.get(1)));
				myPanel.listOfReportsPanel.listOfReports.add(newReport);
				int updatedReportsCounter = (int)myPanel.listOfReportsPanel.listOfReports.get(0)+1;
				myPanel.listOfReportsPanel.listOfReports.set(0, updatedReportsCounter);
				myPanel.listOfReportsPanel.model.addRow(new Object[]{newReport.getReportSideB(),newReport.getReportSideA(),newReport.getEmployee(),newReport.getEngraveDateAsString(),newReport.getQuantity(),newReport.getDiopter(),newReport.getType(),newReport.getOrderID()});
				
				
			}
			else
			if (response.get(0).toString().equalsIgnoreCase("Failed in newEngraveReport"))
			{
				JOptionPane.showMessageDialog(myPanel.myEngravingFrame,
					    "לא ניתן ליצור דו''ח עקב תקלה בתקשורת.","שגיאה",JOptionPane.ERROR_MESSAGE);
			}
			else
			{
				JOptionPane.showMessageDialog(myPanel.myEngravingFrame,
					    "לא ניתן ליצור דו''ח עקב בעיה בבסיס הנתונים.","שגיאה",JOptionPane.ERROR_MESSAGE);
			}
		} 
		catch (Exception e)
		{
			
			//e.printStackTrace();
		}
		
		
		// finally
		waitForDBApproval=false;
		clearFields();
		orderIDTextField.setText("");
		
	
		
	}
	
	/**
	 * Initializes the list of orders tab
	 */
	public void initializeByListOfOrdersTab(ProductionOrder order)
	{
		myPanel.setSelectedIndex(1); // Switch to createReportPanel
		//
		clearFields();
		//
		
		orderIDTextField.setText(String.valueOf(order.getOrderID()));
		remarksTextArea.requestFocus();
		
	}
	
	@Override
	public void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    Color color1 = getBackground();
    Color color2 = color1.darker();
    int w = getWidth();
    int h = getHeight(); 
    GradientPaint gp = new GradientPaint(
            0, 0, color1,
            0, h, color2);

    g2d.setPaint(gp);
    g2d.fillRect(0, 0, w, h);
    }
}
